<template>
  <el-dialog class="public-dialog" title="导入" :modelValue="dialogVisible" align-center width="560" @close="handleClose" :close-on-click-modal="false">
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[8px]">
      第 <span class="font-[600]">1</span> 步：点击下载模版
    </p>
    <a :href="downloadUrl" class="bg-[#FAFAFA] flex items-center justify-center rounded-[4px] py-[12px] cursor-pointer">
      <div class="text-[#3366F1] flex items-center gap-1">
        <el-icon>
          <Download />
        </el-icon>下载模板
      </div>
    </a>
    <p class="text-[14px] text-[#0a1431] leading-[20px] my-[16px]">
      第 <span class="font-[600]">2</span> 步：按照模版要求填写
    </p>
    <p class="text-[14px] text-[#0a1431] leading-[20px] mb-[8px]">
      第 <span class="font-[600]">3</span> 步：上传填写完成的文件
    </p>
    <el-upload ref="upload" v-model:file-list="fileList" accept=".csv,.xml,.xlsx" class="v-import" drag :data="extraData" :action="ossParams.host ? `${ossParams.host}` : ''" :limit="1" :auto-upload="false" :on-exceed="handleExceed" :before-upload="beforeUpload" :on-error="handleUploadError" :on-success="handleUploadSuccess">
      <div class="text-[#3366F1] flex items-center">
        <el-icon>
          <Plus />
        </el-icon>上传文件
      </div>
    </el-upload>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loadings.submit" :disabled="!fileList.length" @click="submit">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>

import api from './api'

import {
  ElMessage,
  ElMessageBox,
  genFileId,
  ElNotification,
} from 'element-plus'
import { ref } from 'vue'
const load = ref(false)
import { getSignature } from "@/api/index.js";

const dialogVisible = ref(false)
const downloadUrl = ref('')

const props = defineProps({
  modelValue: { type: Boolean, default: '' },
  importUrl: { type: String, default: '' },
  // callBack: {
  //   type: Function,
  //   default: query => (query)
  // },
  downloadUrl: { type: String, default: '' },
  tableRef: { type: Object, default: () => ({}) },
  task: Boolean,
})

let loadings = reactive({})
let ossParams = reactive({
  host: '',
})

const emit = defineEmits(['close', 'update:modelValue'])

const fileList = ref([])
const upload = ref()
const extraData = reactive({})
const uploadPercent = ref(0)
const fileName = ref('')

const handleExceed = files => {
  upload.value?.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value?.handleStart(file)
}

const get_suffix = name => {
  const pos = name.lastIndexOf('.')
  let suffix = ''
  if (pos != -1) {
    suffix = name.substring(pos)
  }
  return suffix
}

const beforeUpload = file => {
  if (file.size > 1024 * 1024 * 1024) {
    ElMessage.warning('上传文件大小不能超过1G')
    return false
  }
  uploadPercent.value = 0
  try {
    const { policy, accessId, dir, signature } = ossParams || {}
    const name = `${file.name.split('.')[0]}_${new Date().getTime()}`
    const _fileName = name + get_suffix(file.name)
    extraData.key = dir + _fileName
    extraData.policy = policy
    extraData.OSSAccessKeyId = accessId
    extraData.signature = signature
    fileName.value = _fileName
    return true
  } catch (err) {
    fileName.value = ''
    ElMessage.error(err.message)
    return false
  }
}

const handleUploadSuccess = () => {
  // const [{ downloadUrl }] = arguments
  console.error('ar', arguments)
  // ElMessage({ type: 'success', message: `上传成功` })
  // if (props.callBack && typeof props.callBack === 'function') {
  //   props.callBack({
  //     downloadUrl,
  //     fileName: fileName.value,
  //     ossUrl: extraData.key
  //   })
  // }
}

const handleUploadError = err => {
  fileName.value = ''
  ElMessage.error(`上传失败 ${err.toString()}`)
  uploadPercent.value = 0
}

// 打开弹窗
// const open = async selection => {
//   if (!load.value) {
//     load.value = true
//     await 1
//   }
//   loadings = reactive({})
// }
// 关闭弹窗
const handleClose = () => {
  // emit('update:modelValue', false)
  dialogVisible.value = false
  loadings.submit = false
  fileList.value = []
}

// 提交
const submit = () => {
  loadings.submit = true
  upload.value.submit()
  loadings.submit = false
  // const params = new FormData()
  // fileList.value.forEach(d => {
  //   params.append('file', d.raw)
  // })
  // let dtd = props.importUrl
  // if (props.paramsFormatter && typeof props.paramsFormatter === 'function') {
  //   dtd = props.paramsFormatter(props.importUrl)
  // }
  // api
  //     .submit(props.importUrl, params)
  //     .then(res => {
  //       const skip = res.data?.skip || []
  //       if (res.code === 200) {
  //         emit('success')
  //         ElMessage.success('导入成功')
  //         close()
  //         return
  //       }
  //       if (skip.length) {
  //         ElMessageBox({
  //           title: '导入提示',
  //           confirmButtonText: '跳过导入',
  //           cancelButtonText: '取消导入',
  //           message: h('p', null, [
  //             skip.map(d =>
  //                 h('p', null, `第${d}行中的站点/销售/sku/部门不存在，`)
  //             ),
  //             h('p', null, '是否跳过导入?'),
  //           ]),
  //         })
  //             .then(() => {
  //               skip.forEach(d => {
  //                 params.append('skip[]', d)
  //               })
  //               api.submit(props.importUrl, params).then(res => {
  //                 emit('success')
  //                 ElMessage({ type: 'success', message: '导入成功' })
  //                 close()
  //               })
  //             })
  //             .catch(() => {
  //               ElMessage({ type: 'info', message: '取消操作' })
  //             })
  //       } else {
  //         ElNotification.error({ title: res.message })
  //       }
  //     })
  //     .finally(() => {
  //       loadings.submit = false
  //     })
}
const initUpload = async () => {
  const { data } = await getSignature({ directory: 'import/' })
  console.warn(data)
  ossParams = {
    ...data,
  }
}

onMounted(() => {

  initUpload()
})
const open = async(params = {}) => {
  
  // const { tpl_name } = params
  // const res = await api.getImportTpl({ tpl_name })
  // downloadUrl.value = res.data.url
  // importUrl.value = '/order/batch/operation'
  dialogVisible.value = true
}
defineExpose({

  open,
})
</script>

<style lang="scss" scoped>
.v-import {
  :deep(.el-upload-dragger) {
    padding: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-color: #3366f1;
  }
}
</style>
